package com.pactera.integral.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pactera.integral.common.web.WebResponse;

public class ServiceUnauthorizedEntryPoint implements AuthenticationEntryPoint {

    private static final Logger logger = LoggerFactory.getLogger(ServiceUnauthorizedEntryPoint.class);
    
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException arg2) throws IOException, ServletException {
        // return 401 UNAUTHORIZED status code if the user is not authenticated
        logger.debug(" *** UnauthorizedEntryPoint.commence: " + request.getRequestURI());
//        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"UnAuthentication"+request.getAttribute("message"));
        ObjectMapper mapper = new ObjectMapper();
        WebResponse res = new WebResponse();
        res.setResponseCode("2");
        res.setErrorCode("401");
        String message = (String)request.getAttribute("message");
        res.setMessage(StringUtils.isEmpty(message)?arg2.getMessage():message);
        String jsonString = mapper.writeValueAsString(res);
        PrintWriter writer = response.getWriter();
        writer.write(jsonString);
        writer.flush();
    }

}